package com.huel.fragment;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.huel.bean.Goods;
import com.huel.taobaostore.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class login_Fragment extends Fragment {
    private Mine_fragment mine_fragment;
    private String username;
    private View contextView;
    private EditText usernameEdit;
    private EditText passwordEdit;
    private Index_Fragment index_fragment;
    private Register_Fragment register_fragment;
    private Button mbtn;
    private TextView regBtn;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    // 创建view   也可以直接在这里面获取view中的控件。
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//
        contextView = inflater.inflate(R.layout.fragment_login, container, false);
        //获取控件

        usernameEdit=contextView.findViewById(R.id.et_account);
        passwordEdit=contextView.findViewById(R.id.et_passwordl);
        regBtn =contextView.findViewById(R.id.regBtn);
        mbtn=contextView.findViewById(R.id.btn_login);
        if(getUsername()!=null&&getUsername()!=""){
            usernameEdit.setText(getUsername());
        }
        mbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //在这开启网络请求 判断是否能登录
                judge(usernameEdit.getText().toString(),passwordEdit.getText().toString());
            }
        });
        //设置 下划线效果
        regBtn.setText(Html.fromHtml("<u>"+"没有账号？点我立即注册"+"</u>"));
        regBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //跳转到 注册页面
                getRegister();

            }
        });
        return contextView;
    }
    public  String getData(){
        return usernameEdit.getText().toString() +" "+passwordEdit.getText().toString();
    }
    public void getIndex(String name,String password) {
        if (index_fragment == null ) {
            index_fragment = new Index_Fragment();
        }
        index_fragment.setData(name);
        //创建FragmentManager对象
        FragmentManager manager = getFragmentManager();
        FragmentTransaction fragmentTransaction = manager.beginTransaction();
        fragmentTransaction.replace(R.id.fragment, index_fragment);
        //提交事务
        fragmentTransaction.commit();

    }

    public void getRegister() {
        if (register_fragment == null ) {
            register_fragment = new Register_Fragment();
        }
        //创建FragmentManager对象
        FragmentManager manager = getFragmentManager();
        FragmentTransaction fragmentTransaction = manager.beginTransaction();
        fragmentTransaction.replace(R.id.fragment, register_fragment);
        //提交事务
        fragmentTransaction.commit();
    }

    public void getMine(String username) {
        if (mine_fragment == null ) {
            mine_fragment = new Mine_fragment();
        }
        mine_fragment.setUsername(username);
        //创建FragmentManager对象
        FragmentManager manager = getFragmentManager();
        FragmentTransaction fragmentTransaction = manager.beginTransaction();
        fragmentTransaction.replace(R.id.fragment, mine_fragment);
        //提交事务
        fragmentTransaction.commit();
    }


    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }

    public void judge(String name,String password) {
        OkHttpClient okHttpClient = new OkHttpClient();
        final  String res = name;
        Request request = new Request.Builder()
//                在这拼接字符串  GET请求 很不稳健
                .url("http://192.168.199.229:8080/Android_war_exploded/userServlet?action=login&username=" +name+
                        "&password=" +password)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //失败回调
                System.out.println("请检查网络");
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                String json =response.body().string();//注意response.body().string() 只能调用一次！
                //响应成功,这个回调在子线程中,所以不需要创建线程
                if (response.isSuccessful()) {
                    //isSuccessful方法：如果代码位于（200…300）中，则返回true，这意味着请求已成功接收
                    System.out.println("请求网络Ok");

                    if (json.equals("yes")){
                        //在这写  更新UI操作
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                    getMine(usernameEdit.getText().toString());
                                //跳转 fragment
                            }
                        });
                    }else {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), "账号或者密码错误", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    }





            }
        });
    }
}


